<template>
  <div class="user-security">
    <el-card class="security-card">
      <template #header>
        <span>账户安全</span>
      </template>

      <div class="security-items">
        <!-- 登录密码 -->
        <div class="security-item">
          <div class="security-info">
            <div class="security-icon">
              <el-icon size="24" color="#409eff">
                <Lock />
              </el-icon>
            </div>
            <div class="security-content">
              <h4>登录密码</h4>
              <p>用于保护账户安全，建议定期更换</p>
            </div>
          </div>
          <div class="security-actions">
            <el-button type="primary" @click="showPasswordDialog = true"> 修改密码 </el-button>
          </div>
        </div>

        <!-- 手机绑定 -->
        <div class="security-item">
          <div class="security-info">
            <div class="security-icon">
              <el-icon size="24" color="#67c23a">
                <Iphone />
              </el-icon>
            </div>
            <div class="security-content">
              <h4>手机绑定</h4>
              <p>已绑定：{{ maskPhone(user?.phone) || '未绑定' }}</p>
            </div>
          </div>
          <div class="security-actions">
            <el-button v-if="user?.phone" @click="showPhoneDialog = true"> 更换手机 </el-button>
            <el-button v-else type="primary" @click="showPhoneDialog = true"> 绑定手机 </el-button>
          </div>
        </div>

        <!-- 邮箱绑定 -->
        <div class="security-item">
          <div class="security-info">
            <div class="security-icon">
              <el-icon size="24" color="#e6a23c">
                <Message />
              </el-icon>
            </div>
            <div class="security-content">
              <h4>邮箱绑定</h4>
              <p>已绑定：{{ maskEmail(user?.email) || '未绑定' }}</p>
            </div>
          </div>
          <div class="security-actions">
            <el-button v-if="user?.email" @click="showEmailDialog = true"> 更换邮箱 </el-button>
            <el-button v-else type="primary" @click="showEmailDialog = true"> 绑定邮箱 </el-button>
          </div>
        </div>

        <!-- 安全问题 -->
        <div class="security-item">
          <div class="security-info">
            <div class="security-icon">
              <el-icon size="24" color="#f56c6c">
                <QuestionFilled />
              </el-icon>
            </div>
            <div class="security-content">
              <h4>安全问题</h4>
              <p>{{ hasSecurityQuestions ? '已设置' : '未设置' }}</p>
            </div>
          </div>
          <div class="security-actions">
            <el-button v-if="hasSecurityQuestions" @click="showSecurityQuestionsDialog = true">
              修改问题
            </el-button>
            <el-button v-else type="primary" @click="showSecurityQuestionsDialog = true">
              设置问题
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog 
      v-model="showPasswordDialog" 
      title="修改密码" 
      :width="isMobile ? '90%' : '500px'"
      :top="isMobile ? '5vh' : '15vh'"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
            placeholder="请输入当前密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="changePassword" :loading="changing">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 手机绑定对话框 -->
    <el-dialog
      v-model="showPhoneDialog"
      :title="user?.phone ? '更换手机' : '绑定手机'"
      :width="isMobile ? '90%' : '500px'"
      :top="isMobile ? '5vh' : '15vh'"
    >
      <el-form ref="phoneFormRef" :model="phoneForm" :rules="phoneRules" label-width="100px">
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="phoneForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="验证码" prop="verificationCode">
          <div class="verification-code-input">
            <el-input v-model="phoneForm.verificationCode" placeholder="请输入验证码" />
            <el-button type="primary" :disabled="countdown > 0" @click="sendVerificationCode">
              {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPhoneDialog = false">取消</el-button>
          <el-button type="primary" @click="bindPhone" :loading="binding"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 邮箱绑定对话框 -->
    <el-dialog
      v-model="showEmailDialog"
      :title="user?.email ? '更换邮箱' : '绑定邮箱'"
      :width="isMobile ? '90%' : '500px'"
      :top="isMobile ? '5vh' : '15vh'"
    >
      <el-form ref="emailFormRef" :model="emailForm" :rules="emailRules" label-width="100px">
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="验证码" prop="verificationCode">
          <div class="verification-code-input">
            <el-input v-model="emailForm.verificationCode" placeholder="请输入验证码" />
            <el-button
              type="primary"
              :disabled="emailCountdown > 0"
              @click="sendEmailVerificationCode"
            >
              {{ emailCountdown > 0 ? `${emailCountdown}s` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEmailDialog = false">取消</el-button>
          <el-button type="primary" @click="bindEmail" :loading="emailBinding"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Lock, Iphone, Message, QuestionFilled } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import type { FormInstance, FormRules } from 'element-plus'

const authStore = useAuthStore()

// 响应式断点检测
const isMobile = ref(false)
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

// 响应式数据
const showPasswordDialog = ref(false)
const showPhoneDialog = ref(false)
const showEmailDialog = ref(false)
const showSecurityQuestionsDialog = ref(false)
const changing = ref(false)
const binding = ref(false)
const emailBinding = ref(false)
const countdown = ref(0)
const emailCountdown = ref(0)

const passwordFormRef = ref<FormInstance>()
const phoneFormRef = ref<FormInstance>()
const emailFormRef = ref<FormInstance>()

// 表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

const phoneForm = reactive({
  phone: '',
  verificationCode: '',
})

const emailForm = reactive({
  email: '',
  verificationCode: '',
})

// 表单验证规则
const passwordRules: FormRules = {
  oldPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}

const phoneRules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为6位', trigger: 'blur' },
  ],
}

const emailRules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为6位', trigger: 'blur' },
  ],
}

// 计算属性
const user = computed(() => authStore.user)
const hasSecurityQuestions = computed(() => false) // TODO: 从用户信息中获取

// 方法
const maskPhone = (phone: string | undefined) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

const maskEmail = (email: string | undefined) => {
  if (!email) return ''
  const [username, domain] = email.split('@')
  if (username.length <= 2) return email
  return `${username.substring(0, 2)}***@${domain}`
}

const changePassword = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    changing.value = true

    const result = await authStore.changePassword(
      passwordForm.oldPassword,
      passwordForm.newPassword,
    )

    if (result.success) {
      showPasswordDialog.value = false
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
      ElMessage.success('密码修改成功')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
  } finally {
    changing.value = false
  }
}

const sendVerificationCode = async () => {
  if (!phoneForm.phone) {
    ElMessage.warning('请先输入手机号码')
    return
  }

  try {
    // TODO: 调用发送验证码API
    // await authService.sendPhoneVerificationCode(phoneForm.phone)

    ElMessage.success('验证码已发送')
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    ElMessage.error('发送验证码失败')
  }
}

const sendEmailVerificationCode = async () => {
  if (!emailForm.email) {
    ElMessage.warning('请先输入邮箱地址')
    return
  }

  try {
    // TODO: 调用发送邮箱验证码API
    // await authService.sendEmailVerificationCode(emailForm.email)

    ElMessage.success('验证码已发送')
    emailCountdown.value = 60
    const timer = setInterval(() => {
      emailCountdown.value--
      if (emailCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    ElMessage.error('发送验证码失败')
  }
}

const bindPhone = async () => {
  if (!phoneFormRef.value) return

  try {
    await phoneFormRef.value.validate()
    binding.value = true

    // TODO: 调用绑定手机API
    // await authService.bindPhone(phoneForm.phone, phoneForm.verificationCode)

    ElMessage.success('手机绑定成功')
    showPhoneDialog.value = false
    phoneForm.phone = ''
    phoneForm.verificationCode = ''
  } catch (error) {
    console.error('绑定手机失败:', error)
  } finally {
    binding.value = false
  }
}

const bindEmail = async () => {
  if (!emailFormRef.value) return

  try {
    await emailFormRef.value.validate()
    emailBinding.value = true

    // TODO: 调用绑定邮箱API
    // await authService.bindEmail(emailForm.email, emailForm.verificationCode)

    ElMessage.success('邮箱绑定成功')
    showEmailDialog.value = false
    emailForm.email = ''
    emailForm.verificationCode = ''
  } catch (error) {
    console.error('绑定邮箱失败:', error)
  } finally {
    emailBinding.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  checkMobile()
  window.addEventListener('resize', checkMobile)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})
</script>

<style scoped>
.user-security {
  width: 100%;
}

.security-card {
  margin-bottom: 20px;
}

.security-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  background: #fafafa;
}

.security-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.security-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.security-content h4 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 4px 0;
}

.security-content p {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.verification-code-input {
  display: flex;
  gap: 12px;
}

.verification-code-input .el-input {
  flex: 1;
}

.verification-code-input .el-button {
  width: 120px;
  flex-shrink: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .security-item {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .verification-code-input {
    flex-direction: column;
  }

  .verification-code-input .el-button {
    width: 100%;
  }
  
  /* 弹窗移动端适配 */
  :deep(.el-dialog) {
    margin: 5vh auto !important;
  }
  
  :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  :deep(.el-form-item__label) {
    text-align: left;
    padding-bottom: 8px;
  }
  
  .dialog-footer {
    text-align: center;
    
    .el-button {
      width: 100%;
      margin: 5px 0;
    }
  }
}
</style>
